<template>
  <InfoCard>
    <template #header v-if="payInfo.item.button?.buttonUp">
      <div class="text-center" v-html="payInfo.item.button?.buttonUp"></div>
    </template>
    <template #content>
      <div style="text-align: center" v-if="payInfo.item?.button">
        <Button
          style="padding: 2px 8px"
          size="small"
          @click="goto(LINK)"
          :color="payInfo.item.button?.buttonStyle"
          >{{ payInfo.item.button?.popTitle }}</Button
        >
        <div class="text-center" v-html="payInfo.item.button?.buttonDown"></div>
      </div>
    </template>
  </InfoCard>
</template>
<script setup lang="ts">
import { onMounted, ref } from 'vue'
import InfoCard from './InfoCard.vue'
import { Button } from 'vant'

const LINK = ref('')

const props = defineProps({
  payInfo: {
    type: Object,
    default: () => ({})
  }
})

function linkFormat() {
  const payMessage = props.payInfo.payMessage

  // 先替换payMessage里除了input的其他字段内容
  let res = LINK.value.replace(/\{(.*?)\}/g, function (match, key) {
    console.log(match)
    if (key === 'payMessage') return ''
    if (payMessage?.[key]) return payMessage?.[key]
    return match
  })

  console.log(res)

  if (res !== undefined && res !== null) {
    LINK.value = res
  }

  console.log(LINK.value)
  
  res = LINK.value.replace(/\{(.*?)\}/g, function (match, key) {
    return payMessage?.input?.find((item) => item.title === key)?.value
      ? payMessage?.input?.find((item) => item.title === key)?.value
      : match
  })

  if (res !== undefined && res !== null) {
    LINK.value = res
  }

  // 转义URL
  let arr = LINK.value.split('url=')
  if (arr.length > 1) {
    LINK.value = arr[0] + 'url=' + encodeURIComponent(arr[1])
  }

  console.log(LINK.value)
}

onMounted(() => {
  LINK.value = props.payInfo.item.button?.buttonEvent
  linkFormat()
})

function goto(url: string) {
  switch (props.payInfo.item.button?.buttonCopy) {
    case '1':
      navigator.clipboard.writeText(props.payInfo.payMessage?.amount)
      break
    case '2':
      navigator.clipboard.writeText(props.payInfo.orderNo)
      break
    case '3':
      navigator.clipboard.writeText(props.payInfo.item?.captcha?.captcha)
      break
  }
  window.location.href = url
}
</script>
